﻿using BookLink.Data;
using BookLink.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;

namespace BookLink.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        private readonly BookLinkContext _context;
        private readonly IConfiguration _configuration;

        public IndexModel(ILogger<IndexModel> logger, BookLink.Data.BookLinkContext context, IConfiguration configuration)
        {
            _logger = logger;
            this._context = context;
            this._configuration = configuration;
        }

        public PaginatedList<Book> Book { get; set; } = default!;
        [BindProperty(SupportsGet = true)]
        public string? SearchString { get; set; }

        //public void OnGet()
        //{

        //}

        public async Task OnGetAsync(string searchString, int? pageIndex)
        {
            var books = from b in _context.Book
                        select b;

            SearchString = searchString;
            if (!string.IsNullOrEmpty(SearchString))
            {
                books = books.Where(x => x.IsDeleted == 0).Where(x => x.IsVisible).Where(x => x.Title.Contains(SearchString) || x.Genre.Contains(SearchString));
            }

            var pageSize = _configuration.GetValue("PageSize", 10);
            var deepCount = _configuration.GetValue("DeepCount", 30);
            books = books.OrderByDescending(x => x.CreationAt).Take(deepCount);

            Book = await PaginatedList<Book>.CreateAsync(books.AsTracking(), pageIndex ?? 1, pageSize);
        }
    }
}